package com.duowei.diandan.fragment;

import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.WorkerThread;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.duowei.diandan.R;
import com.duowei.diandan.app.InitManager;
import com.duowei.diandan.app.OrderList;
import com.duowei.diandan.bean.QrCodePay;
import com.duowei.diandan.constant.QrCodeType;
import com.duowei.diandan.databinding.QrCodePay2FragmentBinding;
import com.duowei.diandan.db.entry.PaySet;
import com.duowei.diandan.db.entry.Wmlsbjb;
import com.duowei.diandan.event.ToastEvent;
import com.duowei.diandan.util.DateTimes;
import com.duowei.diandan.util.NetUtils;

import org.greenrobot.eventbus.EventBus;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Random;

import okhttp3.ResponseBody;

public class QrCodePay2Fragment extends BaseFragment {
    public static final String TAG = "QrCodePay2Fragment";

    private QrCodePay2FragmentBinding mBinding;
    private QrCodeType mType;

    private String mPayUrl;
    private String mPayQueryUrl;
    private String mWeiOrZfbId;
    private float mPayMoney;

    private Handler mHandler = new Handler();

    private QrCodePay mQrCodePay = new QrCodePay();

    private OnStatusListener mOnStatusListener;

    public void setOnStatusListener(OnStatusListener onStatusListener) {
        mOnStatusListener = onStatusListener;
    }

    public interface OnStatusListener {

        void onCloseClick();

        void onPaySuccess();

    }

    public static QrCodePay2Fragment newInstance(QrCodeType type, float payMoney) {

        Bundle args = new Bundle();
        args.putString("QrCodeType", type.name());
        args.putFloat("PayMoney", payMoney);

        QrCodePay2Fragment fragment = new QrCodePay2Fragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            mType = QrCodeType.valueOf(args.getString("QrCodeType"));
            mPayMoney = args.getFloat("PayMoney");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_qr_code_pay2, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        mQrCodePay.setPrice(mPayMoney);
        OrderList.getInstance().setQrCodePay(null);

        mBinding.closeLayout.setOnClickListener(v -> {
            if (mOnStatusListener != null) {
                mOnStatusListener.onCloseClick();
            }
        });

        mBinding.payMoneyView.setPrice(mPayMoney);

        if (mType == QrCodeType.WECHATPAY) {
            mBinding.bottomMessageView.setText("请使用微信扫一扫进行付款");
            mQrCodePay.setTitle("微信支付");

            new Thread(mProcessDataRunnable).start();

        } else if (mType == QrCodeType.ALIPAY) {
            mBinding.bottomMessageView.setText("请使用支付宝扫一扫进行付款");
            mQrCodePay.setTitle("支付宝支付");

            new Thread(mProcessDataRunnable).start();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPayQueryThread != null) {
            mPayQueryThread.interrupt();
        }
    }

    private int getNumber() {
        Random random = new Random();
        return random.nextInt(100000);
    }

    private Runnable mProcessDataRunnable = () -> {
        if (mType == QrCodeType.WECHATPAY || mType == QrCodeType.ALIPAY) {
            mHandler.post(() -> {
                mBinding.qrCodeProgressBar.setVisibility(View.VISIBLE);
                mBinding.qrCodeMsgView.setVisibility(View.GONE);
            });
        }

        PaySet ps = getDb().paySetDao().findOne();
        if (ps == null) {
            showMessage("没有支付信息设置");

        } else {
            // Url中文处理
            String by2 = "";
            if (!TextUtils.isEmpty(ps.getBy2())) {
                try {
                    by2 = URLEncoder.encode(ps.getBy2(), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    Log.e(TAG, "handlePay: ", e);
                    by2 = ps.getBy2();
                }
            }

            //生成10W以内随机数
            mWeiOrZfbId = DateTimes.getTime() + getNumber();

            // 根据支付设置处理url
            if (mType == QrCodeType.WECHATPAY) {
                // 微信
                if (TextUtils.isEmpty(ps.getBy3())) {
                    showMessage("未设置微信支付功能");
                    return;
                }
                //判断使用哪个接口
                if ("原生态接口".equals(ps.getBy7())) {
                    //如果是原生态接口调用这个
                    mPayUrl = "http://" + ps.getFwqdz() + "/yst/pay/native_dynamic_qrcode.php" +
                            "?weid=" + ps.getBy3() +
                            "&orderid=" + mWeiOrZfbId +
                            "&money=" + mPayMoney +
                            "&name=" + ps.getBy1() + by2;

                    mPayQueryUrl = "http://" + ps.getFwqdz() + "/yst/pay/order_query.php" +
                            "?orderid=" + mWeiOrZfbId +
                            "&weid=" + ps.getBy3();
                } else {
                    //如果是服务商接口调用这个
                    mPayUrl = "http://" + ps.getFwqdz() + "/dl/sys/demo/native_dynamic_qrcode.php" +
                            "?weid=" + ps.getBy3() +
                            "&orderid=" + mWeiOrZfbId +
                            "&money=" + mPayMoney +
                            "&name=" + ps.getBy1() + by2;

                    mPayQueryUrl = "http://" + ps.getFwqdz() + "/bs/wxzf/order_query.php" +
                            "?orderid=" + mWeiOrZfbId +
                            "&weid=" + ps.getBy3();
                }


            } else if (mType == QrCodeType.ALIPAY) {
                // 支付宝
                if (TextUtils.isEmpty(ps.getPid())) {
                    showMessage("未设置支付宝支付功能");
                    return;
                }

                mPayUrl = "http://" + ps.getFwqdz() + "/aipay/f2fpay/qrpay.php" +
                        "?appid=" + ps.getPid() +
                        "&out_trade_no=" + mWeiOrZfbId +
                        "&subject=" + ps.getBy1() + by2 +
                        "&store_id=" + ps.getBy1() +
                        "&total_amount=" + mPayMoney;

                mPayQueryUrl = "http://" + ps.getFwqdz() + "/aipay/f2fpay/query.php" +
                        "?out_trade_no=" + mWeiOrZfbId +
                        "&appid=" + ps.getPid();

            }

            if (mType == QrCodeType.WECHATPAY || mType == QrCodeType.ALIPAY) {
                // 提取二维码
                mHandler.post(() -> mBinding.qrCodeProgressBar.setVisibility(View.VISIBLE));
                try {
                    String result = NetUtils.get(mPayUrl).body().string();
                    mHandler.post(() -> {
                        mBinding.qrCodeProgressBar.setVisibility(View.GONE);
                    });

                    Document doc = Jsoup.parse(result);
                    Elements imgs = doc.getElementsByTag("img");
                    for (Element img : imgs) {
                        String imgSrc = img.attr("src");

                        if (!TextUtils.isEmpty(imgSrc)) {
                            ResponseBody body = NetUtils.get(imgSrc).body();
                            if (body != null) {
                                InputStream is = body.byteStream();
                                BufferedInputStream bis = new BufferedInputStream(is);
                                Bitmap bitmap = BitmapFactory.decodeStream(bis);
                                mHandler.post(() -> mBinding.qrCodeImageView.setImageBitmap(bitmap));

                                QrCodePay2Fragment.this.mPayQueryThread = new Thread(QrCodePay2Fragment.this.mPayQueryRunnable);
                                QrCodePay2Fragment.this.mPayQueryThread.start();
                            }

                            break;
                        }
                    }

                } catch (IOException e) {
                    Log.d(TAG, "", e);
                    mHandler.post(() -> mBinding.qrCodeProgressBar.setVisibility(View.GONE));
                }

            }
        }
    };

    private void showMessage(String message) {
        EventBus.getDefault().post(new ToastEvent(message, false));
    }

    private Thread mPayQueryThread;

    private Runnable mPayQueryRunnable = () -> {

        while (true) {
            if (Thread.currentThread().isInterrupted()
                    || InitManager.getInstance().getCountdownSecond() <= 0) {
                break;
            }

            try {
                String result = NetUtils.get(mPayQueryUrl).body().string();

                if (result.contains("支付成功") || result.contains("SUCCESS")) {
                    Thread.currentThread().interrupt();

                    paySuccess(result);
                } else {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }

            } catch (IOException e) {
                Log.e(TAG, "PayQueryRunnable", e);

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e1) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    };

    @WorkerThread
    private void paySuccess(String result) {
        String zfbid = null;
        if (mType == QrCodeType.ALIPAY) {
            zfbid = result.substring(result.indexOf("*") + 1, result.length());
        }

        // --
        Wmlsbjb wmlsbjb = getDb().wmlsbjbDao().findOne();
        wmlsbjb.setBy13(mWeiOrZfbId);
        wmlsbjb.setBy16(zfbid);
        getDb().wmlsbjbDao().update(wmlsbjb);

        mHandler.post(() -> {
            mBinding.qrCodeMsgView.setVisibility(View.VISIBLE);
            mBinding.qrCodeMsgView.setText("付款成功");
            OrderList.getInstance().setQrCodePay(mQrCodePay);

            if (mOnStatusListener != null) {
                mOnStatusListener.onPaySuccess();
            }
        });
    }
}
